package com.android.basiclib.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.android.basiclib.receiver.ConnectivityReceiver;
import com.android.basiclib.uitls.Log.LogUtil;

/**
 * 普通的Fragment，基类Fragment
 */

public abstract class AbsFragment extends Fragment implements ConnectivityReceiver.ConnectivityReceiverListener {

    /**
     * 获取Context对象
     */
    protected Activity mActivity;
    protected Context mContext;

    /**
     * 获取layout的id，具体由子类实现
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化操作
     */
    protected abstract void init();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        mContext = getActivity().getApplicationContext();

        if (needRegisterNetworkChangeObserver())
            ConnectivityReceiver.registerObserver(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {

//        long start = System.currentTimeMillis();
        View view = inflater.inflate(getLayoutResId(), container, false);
//        long jiazai = System.currentTimeMillis() - start;
//        LogUtil.e("Fragment加载时间：" + jiazai);
        initViews(view);
        return view;
    }

    protected void initViews(View view) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /**  相关的init方法**/
        init();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    /**
     * 只映射了onDestroy方法 取消任务
     */
    @Override
    public void onDestroy() {
        super.onDestroy();

        if (needRegisterNetworkChangeObserver())
            ConnectivityReceiver.unregisterObserver(this);
    }


    /**
     * 是否需要注册监听网络变换
     */
    protected boolean needRegisterNetworkChangeObserver() {
        return true;
    }

}
